package com.fms.sys.service.impl;

import com.fms.sys.entity.Note;
import com.fms.sys.mapper.NoteMapper;
import com.fms.sys.service.INoteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.client.RestTemplate;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Jinfeng
 * @since 2023-03-18
 */
@Service
public class NoteServiceImpl extends ServiceImpl<NoteMapper, Note> implements INoteService {

    // Server酱SendKey（请替换为你的真实SendKey）
    private static final String SERVER_CHAN_KEY = "SCT278343TYZSUB35G7JHg0lmuZ1FcWjvA";

    /**
     * 每分钟检测未完成且到期的备忘录并推送提醒
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void sendNoteReminders() {
        int minutesBefore = 10; // 提前10分钟提醒
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime remindTime = now.plusMinutes(minutesBefore);

        QueryWrapper<Note> wrapper = new QueryWrapper<>();
        wrapper.eq("status", "未完成");
        wrapper.eq("is_reminded", 0); // 只查未提醒的
        wrapper.le("deadline", remindTime);
        wrapper.gt("deadline", now); // 只查还没到期的

        List<Note> dueNotes = this.list(wrapper);
        for (Note note : dueNotes) {
            // 推送到微信
            pushToWechat(SERVER_CHAN_KEY, "备忘录提前提醒",
                    "标题：" + note.getTitle() +
                            "\n内容：" + note.getContent() +
                            "\n优先级：" + note.getPriority() +
                            "\n截止日期：" + note.getDeadline());
            // 标记为已提醒
            note.setIsReminded(1);
            this.updateById(note);
        }
    }

    private void pushToWechat(String sendKey, String title, String content) {
        try {
            String url = "https://sctapi.ftqq.com/" + sendKey + ".send?title="
                    + title + "&desp=" + content;
            RestTemplate restTemplate = new RestTemplate();
            String result = restTemplate.getForObject(url, String.class);
            System.out.println("Server酱推送结果：" + result);
        } catch (Exception e) {
            System.err.println("Server酱推送失败：" + e.getMessage());
        }
    }
}
